#!/usr/local/bin/php -q
<?php

require ('../conf/config.inc');
require_once COMMON_LIB.'DVS/DVS.php';
require_once COMMON_LIB.'DVS/Dynamic.php';

//require_once (PROJECT_ROOT.'/layout/getXML.php');

require ('HTTP/Request2.php');
require (PROJECT_ROOT.'/layout/getDataHA.php');

define('DEBUG', 0);

set_time_limit (7200);
set_time_limit (7200);


function showForm()
{
    $str = 'VillaSearch:<br><br><form method=post action="">'
            .'location_id: <input type="text" name="location_id"><br>'
            .'<input type="submit" value=">>"></form>';
    echo $str.'<br>';
}

$op = 'VillaSearch';
//showMenu();

//print_r($_REQUEST);

if (!$_POST && !$_GET) {
    showForm();
    exit;
}


$location_id = DVS::getVar('location_id', 'word', 'request');

$dir = PROJECT_ROOT.'data/'.date('Ymd').'_reg';
@mkdir($dir);

//$regions_tpl = '/<a href="\/([^"]+)" class="region-refinement">\n[\s]+([^\n]+)([^<]+)</';
//$regions_tpl = '/\/([^\/]+)\/\w?\/?(\d+)(.htm|\/fa\/find.squery|)" class="region-refinement">\n[\s]+([^\n]+) rentals[^(]+\(([^)]+)/';

    /**
    1 link
    2 alias
    3 id
    5 name
    6 counter
    */
//$regions_tpl = '/\/(([^\/]+)\/\w?\/?(\d+)(.htm|\/fa\/find.squery|))" class="region-refinement">\n[\s]+([^\n]+) rentals[^(]+\(([^)]+)/';
//$regions_tpl = '/\/([a-z-]+(\/[a-z-]+)?\/[^0-9]?(\d+)(.htm|\/fa\/find.squery|))" class="region-refinement">\n[\s]+([^\n]+) rentals[^(]+\(([^)]+)/i';

$data_obj = new GetDataHA;
$start_time = time();

if ($location_id) {
    echo $location_id.'<p>';
    $data_obj->data_url['Search']['url'] = $location_id;
} else {
    $location_id = 1;
}

    $body = $data_obj->requestData('Search');
    if (strlen($body) > 1024) {
        //echo $body;
        file_put_contents($dir.'/'.$location_id.'.htm', $body);
        $regions_tpl = '/"\/(([^0-9]+)(\d+)[^"]{0,})" class="region-refinement">\n[\s]+([^\n]+) rentals[^(]+\(([^)]+)/i';
        preg_match_all ($regions_tpl, $body, $regions_match);
        getRegions($regions_match);
    }



//echo '<pre>';
//print_r($regions_match);
//exit;


getRegions($regions_match);

    function getRegions($url_arr)
    {
        global $dir, $data_obj, $regions_tpl;
        //print_r($url_arr);
        foreach ($url_arr[1] as $k => $url) {
            $data_obj->data_url['Search']['url'] = $url;
            $file_name = $dir.'/'.$url_arr[3][$k].'.htm';
            $body = $data_obj->requestData('Search');
            if (!file_exists($file_name)) {
                echo '<b>'.$url.' => '.$url_arr[3][$k].'</b><br>';
                if (strlen($body) > 1024) {
                    file_put_contents($file_name, $body);
                }
            }
            preg_match_all ($regions_tpl, $body, $regions_match);
            if ($regions_match) {
                getRegions($regions_match);
            }
            //flush();
        }
    }




$end_time = time();
echo '<br>t: '.($end_time - $start_time).'c.<br>';

?>